import {
  reqMerchandiseDetail,
  reqOrderSubmit,
  reqAddToCart,
  reqAssessList,
  reqminimallAdd,
  reqminimallCheck
} from "../../api/good"
import {
  setStorage,
  removeStorage,
  clearStorage
} from '../../utils/storage'
import {
  toast
} from '../../utils/extendApi'

const BigNumber = require('bignumber.js');
// pages/good/good.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    specificationshow: false,
    commentshow: false,
    cartaddshow: false,
    amount: 1,
    specifications: [],
    selectedSpecs: {},
    parametershow: false,
    merchandiseId: '',
    images: '',
    cheapest: '',
    productionDate: '',
    shelfLife: '',
    sourceofGoods: '',
    supplierId: '',
    temperatureRequirement: '',
    manufacturer: '',
    merchandiseCategory: '',
    merchandiseDescription: '',
    merchandiseName: '',
    merchandiseImageList: [],
    selectedSpecsPrice: '',
    assessList: {},
    type: false,
    businessType:'',
    ReferenceId:''
  },

  onclosecartadd() {
    this.setData({
      cartaddshow: false
    })
  },

  onopencartadd() {
    this.setData({
      cartaddshow: true
    })
  },

  onclosespecification() {
    this.setData({
      specificationshow: false
    })
  },

  onopenspecification() {
    this.setData({
      specificationshow: true
    })
  },

  oncloseparameter() {
    this.setData({
      parametershow: false
    })
  },

  onopenparameter() {
    this.setData({
      parametershow: true
    })
  },

  onclosecomment() {
    this.setData({
      commentshow: false
    })
  },

  onopencomment() {
    this.setData({
      commentshow: true
    })
    this.showcommentdetail()
  },

  onamountChange(event) {
    this.setData({
      amount: event.detail
    })
    let price = new BigNumber(this.data.selectedSpecs.price)
    if(this.data.selectedSpecs.discountPrice){
      price = new BigNumber(this.data.selectedSpecs.discountPrice)
    }
    let quantity = new BigNumber(this.data.amount)
    let total = price.multipliedBy(quantity).toString()

    this.setData({
      selectedSpecsPrice: total
    })

    // console.log(this.data.selectedSpecsPrice)
    // console.log(this.data.amount)
  },

  back() {
    wx.navigateBack()
  },

  selectParam(e) {
    const value = e.currentTarget.dataset.selectspec;
    // console.log(value)
    this.setData({
      selectedSpecs: value,
    });
    let price = new BigNumber(value.price)
    if(value.discountPrice){
      price = new BigNumber(value.discountPrice)
    }
    let quantity = new BigNumber(this.data.amount)
    let total = price.multipliedBy(quantity).toString()

    this.setData({
      selectedSpecsPrice: total
    })

    // console.log(this.data.selectedSpecsPrice)
  },

  onLoad(options) {
    const merchandiseId = options.productId
    const businessType = options.businessType
    const ReferenceId = options.ReferenceId
    
    //这个type字段其实只是用来区别是主播往小商城添加商品还是用户正常购买
    //上面的businessType才是真的确定用户是从哪个地方进来的
    const type = options.type


    if (merchandiseId) {
      this.setData({
        merchandiseId: merchandiseId
      })
    }

    if (type) {
      this.setData({
        type: true
      })
    }

    if (businessType) {
      this.setData({
        businessType: businessType
      })
    }

    if(ReferenceId){
      this.setData({
        ReferenceId:ReferenceId
      })
    }

    this.getMerchandiseDetail(merchandiseId)

  },

  async getMerchandiseDetail(productId) {
    const {
      data
    } = await reqMerchandiseDetail(productId)
    // console.log(data)
    const items = data.goods
    let minPrice = Infinity; // 初始化为无穷大


    //选择该商品下任一规格判断该商品是否有折扣
    //如果有折扣 则显示折扣价中的最低价格
    //否则显示原价中的最低价格
    if (items[0].discountPrice == null) {
      for (let i = 0; i < items.length; i++) {
        if (items[i].price < minPrice) {
          minPrice = items[i].price;
        }
      }
    }
    else{
      for (let i = 0; i < items.length; i++) {
        if (items[i].discountPrice < minPrice) {
          minPrice = items[i].discountPrice;
        }
      }
    }

    const date = new Date(data.productionDate);
    const productionDate = date.toISOString().split('T')[0]; // 默认格式

    // console.log(minPrice)

    this.setData({
      specifications: data.goods,
      images: data.merchandiseImageList,
      cheapest: data.cheapest,
      productionDate: productionDate,
      shelfLife: data.shelfLife,
      sourceofGoods: data.sourceOfGoods,
      supplierId: data.supplierId,
      temperatureRequirement: data.temperatureRequirement,
      manufacturer: data.manufacturer,
      merchandiseCategory: data.merchandiseCategory,
      merchandiseDescription: data.merchandiseDescription,
      merchandiseName: data.merchandiseName,
      selectedSpecs: data.goods[0],
      cheapest: minPrice,
      merchandiseImageList: data.merchandiseImageList
    })

    let price = new BigNumber(data.goods[0].price)
    if(data.goods[0].discountPrice){
      price = new BigNumber(data.goods[0].discountPrice)
    }
    let quantity = new BigNumber(this.data.amount)
    let total = price.multipliedBy(quantity).toString()

    // console.log(total)

    this.setData({
      selectedSpecsPrice: total
    })

    console.log(this.data.selectedSpecsPrice)
  },

  async purchase() {
    const param = [{
      productId: this.data.selectedSpecs.productId,
      amount: this.data.amount,
      referenceId:this.data.ReferenceId,
      businessType:this.data.businessType
    }]

    const {
      data
    } = await reqOrderSubmit(param)
    // console.log(data)
    removeStorage('ordersubmitgoods')
    setStorage('ordersubmitgoods', data)
    wx.navigateTo({
      url: '/pages/ordersubmit/ordersubmit',
    })
  },

  async addtocart() {
    const param = {
      productId: this.data.selectedSpecs.productId,
      amount: this.data.amount
    }

    const res = await reqAddToCart(param)
    // console.log(res)

    if (res.code) {
      wx.toast({
        title: '添加成功',
        icon: 'success'
      })

      this.onclosecartadd()
    }
  },

  async showcommentdetail() {
    const merchandiseId = this.data.merchandiseId
    const {
      data
    } = await reqAssessList(merchandiseId)
    console.log(data)
    this.setData({
      assessList: data
    })
  },


  async addtominimall() {


    const param = {
      merchandiseId: this.data.merchandiseId
    }

    const {
      data
    } = await reqminimallCheck(param)

    if (data) {
      wx.toast({
        title: '该商品已存在',
        icon: 'error'
      })
    } else {
      await reqminimallAdd(param)
      wx.toast({
        title: '商品添加成功',
        icon: 'success'
      })
    }
  }


})